package com.daocao.hua.fragment;

import android.Manifest;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.activity.Application;
import com.daocao.hua.activity.LoanAgreementActivity;

import com.daocao.hua.R;
import com.daocao.hua.activity.MainActivityNew;
import com.daocao.hua.activity.PermissionActivity;
import com.daocao.hua.activity.RepayResultActivity;
import com.daocao.hua.activity.ShenHeActivity;
import com.daocao.hua.activity.V3RepayMoneyActivity;
import com.daocao.hua.api.requestInfo.RepayMoneyRequest;
import com.daocao.hua.api.callback.RepayMoneyContract;
import com.daocao.hua.event.BannerEvent;
import com.daocao.hua.event.OnRepayEventMsg;
import com.daocao.hua.event.SelectMoneyEvent;
import com.daocao.hua.model.ConfirmDilaogModel;
import com.daocao.hua.model.RepayStatusDialogModel;
import com.daocao.hua.util.FlashingTextUtil;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.OnHomeEventMsg;
import com.daocao.hua.impl.RepayInfoImpl;
import com.daocao.hua.http.InfoCallBack;
import com.daocao.hua.model.RepayModel;
import com.daocao.hua.model.ResponseModel;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.CircularProgress;
import com.daocao.hua.view.Dialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by luochuang on 17/4/5..
 * 还钱界面
 */
public class RepayFragment extends BaseFragment implements View.OnClickListener, RepayMoneyContract.View {
//    private View view;
    /**
     * 还钱 控件
     */
    private SwipeRefreshLayout mRepaySwipeRefresh;
    private TextView money, deadline, loanMoney, loanDay, loanTip, day, dayTv, tvBalance, tvOverdueMoney, tvOverdueTip;
    private RelativeLayout repayView;
    private RelativeLayout nothingView;
    private String dealId, mMoney, overdue;
    private float newMoney;
    private boolean isRepay = false;
    private CircularProgress loading;
    private float balance;
    private float Month_need_all_repay_money;


    private BannerEvent bannerEvent = new BannerEvent();
    private RepayMoneyRequest api;
    private boolean isFirstDialog = true;
    private String notice_sn;

    @Override
    protected int setLayoutId() {
        return R.layout.repay_view;
    }

    @Override
    protected void initView() {
        //注册订阅者
        EventBus.getDefault().register(this);
        initRepayView();
        api = RepayMoneyRequest.create();
        api.attachView(this);
    }


    /**
     * 初始化还钱控件
     */
    private void initRepayView() {


        money = (TextView) findView(R.id.money);
        deadline = (TextView) findView(R.id.deadline);
        loanMoney = (TextView) findView(R.id.loan_money);
        loanDay = (TextView) findView(R.id.loan_day);
        loanTip = (TextView) findView(R.id.loan_tip);
        tvBalance = (TextView) findView(R.id.loan_balance);
        tvOverdueMoney = (TextView) findView(R.id.overdue_money);
        day = (TextView) findView(R.id.day);
        dayTv = (TextView) findView(R.id.day_tv);
        tvOverdueTip = findView(R.id.tv_overdue_tip);
        repayView = (RelativeLayout) findView(R.id.repay_view);
        nothingView = (RelativeLayout) findView(R.id.nothing_view);
        ((TextView) findView(R.id.check)).setOnClickListener(this);
        ((TextView) findView(R.id.repay_now)).setOnClickListener(this);
        ((TextView) findView(R.id.loan_now)).setOnClickListener(this);
        loading = (CircularProgress) findView(R.id.progressBar);
        //刷新
        mRepaySwipeRefresh = (SwipeRefreshLayout) findView(R.id.swipe_refresh);
        mRepaySwipeRefresh.setColorSchemeResources(R.color.d_refresh_color_red);
        mRepaySwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                EventBus.getDefault().post(bannerEvent);
                mRepaySwipeRefresh.setRefreshing(true);
                getRepayInfo(mRepaySwipeRefresh);
            }
        });
        if (((MainActivityNew) getActivity()).checkVersion()) {
            getRepayInfo(null);
        }
    }


    @Override
    public void onClick(View v) {
        if (UI.isFastClick()) {
            return;
        }
        /**
         * 还钱
         */
        switch (v.getId()) {
            case R.id.repay_now:
                api.getRepayDialog();
//                gotoRepayAct();
                break;
            case R.id.loan_now:
                if (PreferenceUtils.getBoolean(getContext(), "is_locat", false)) {
                    EventBus.getDefault().post(new SelectMoneyEvent());
                } else {
                    checkPermission(new PermissionActivity.CheckPermListener() {
                                        @Override
                                        public void superPermission() {
                                            PreferenceUtils.putBoolean(Application.getInstance(), "is_locat", true);
                                            ((MainActivityNew) getActivity()).initLocation();
                                        }
                                    }, R.string.location_p, R.string.get_location,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.READ_PHONE_STATE);
                }
//                EventBus.getDefault().post(new SelectMoneyEvent());
                break;
            case R.id.check:
                Intent intent = new Intent(getContext(), LoanAgreementActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("deal_id", dealId);
                getActivity().startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }


    /**
     * 余额还款
     */
    private void getNormalRepay() {
        if (loading != null) loading.setVisibility(View.VISIBLE);
        new RepayInfoImpl().getNormalRepay(getContext(), dealId, "0", new InfoCallBack() {
            public void onFailure(String paramAnonymousString) {
                if (loading != null) loading.setVisibility(View.GONE);
                ToastUtil.makeText(getContext(), paramAnonymousString, Toast.LENGTH_LONG).show();
                repayResultActivity(0);
            }

            public void onSuccess(Object paramAnonymousObject) {
                ResponseModel model = (ResponseModel) paramAnonymousObject;
                if (loading != null) loading.setVisibility(View.GONE);
                ToastUtil.makeText(getContext(), model.getMsg(), Toast.LENGTH_LONG).show();
                repayResultActivity(1);
            }
        });
    }


    private void repayResultActivity(int paramInt) {
        Intent intent = new Intent(getContext(), RepayResultActivity.class);
        intent.putExtra("type", paramInt);
        intent.putExtra("deal_id", dealId);
        intent.putExtra("money", mMoney);
        intent.putExtra("overdue", overdue);

        getActivity().startActivity(intent);
        getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
    }

    /**
     * 获取还款信息
     */
    private void getRepayInfo(final SwipeRefreshLayout refreshLayout) {
        new RepayInfoImpl().getRepayInfo(getContext(), new InfoCallBack() {
            @Override
            public void onSuccess(Object o) {
//                try {
                if (refreshLayout != null) refreshLayout.setRefreshing(false);
                RepayModel model = (RepayModel) o;
                if (TextUtils.isEmpty(model.getData().getId())) {
                    PreferenceUtils.putBoolean(getContext(), "hasRepay", false);
                    initRepayV();
                    return;
                }

                balance = model.getData().getUser_balance();
                tvBalance.setText("￥" + new DecimalFormat("0.00").format(balance));
                tvOverdueMoney.setText(model.getData().getImpose_all_money_format());
                model.getData().getImpose_all_money_format();
                Month_need_all_repay_money = model.getData().getMonth_need_all_repay_money();

                if (model.getData().getUser_balance() >= model.getData().getMonth_need_all_repay_money()) {
                    isRepay = true; //足够余额，直接付款
                } else {
                    isRepay = false;
                }

                dealId = model.getData().getId();
                mMoney = model.getData().getNeed_repay_money_format();

                if (!TextUtils.isEmpty(mMoney)) {
                    if (mMoney.contains("￥")) mMoney = mMoney.replace("￥", "");
                    if (mMoney.contains(",")) mMoney = mMoney.replace(",", "");
                }

                if (model.getData().getUser_balance() != 0)
                    newMoney = Float.parseFloat(mMoney) - model.getData().getUser_balance();
                else
                    newMoney = Float.parseFloat(mMoney);

                overdue = model.getData().getImpose_all_money_format();

                if (model.getData().getImpose_day() > 0) {

                    deadline.setTextColor(ContextCompat.getColor(getContext(), R.color.left_repay_day_tishi_color));
                    day.setText(" " + model.getData().getImpose_day() + " ");
                    day.setVisibility(View.VISIBLE);
                    dayTv.setVisibility(View.VISIBLE);
                    deadline.setText(model.getData().getRepay_day_format() + "前还款，");
                    tvOverdueTip.setText("已逾期");
//                        spark(dayTv);
                    new FlashingTextUtil().spark(getContext(), getActivity(), tvOverdueTip);
                    new FlashingTextUtil().spark(getContext(), getActivity(), dayTv);
                } else {

                    if (model.getData().getRemaining_days() == 0 && model.getData().getImpose_day() == 0) {
                        deadline.setText(getContext().getResources().getString(R.string.repay_tishi3));
                        deadline.setTextColor(ContextCompat.getColor(getContext(), R.color.red_text));
                        day.setVisibility(View.GONE);
                        dayTv.setVisibility(View.GONE);
                    } else {
                        dayTv.setVisibility(View.VISIBLE);
                        day.setVisibility(View.VISIBLE);
                        day.setText(" " + model.getData().getRemaining_days() + " ");
                        deadline.setText(model.getData().getRepay_day_format() + getContext().getResources().getString(R.string.repay_tishi) + " ");
                        deadline.setTextColor(ContextCompat.getColor(getContext(), R.color.left_repay_day_tishi_color));
                    }
                }

                String oMoney = model.getData().getNeed_repay_money_format().replace("￥", "");
//                if (oMoney.contains("."))
//                    newMoney = oMoney.substring(0, oMoney.indexOf('.'));
                money.setText(oMoney);
                loanMoney.setText(model.getData().getMonth_repay_money_format());
                loanDay.setText(model.getData().getRepay_time_format());
                loanTip.setText(model.getData().getMonth_manage_money_format());
//                    overdueMoney.setText(overdue);

                PreferenceUtils.putBoolean(getContext(), "hasRepay", true);
//                弹窗口


                initRepayV();
                if (isFirstDialog) {
                    api.getRepayDialog();
                }
            }

            @Override
            public void onFailure(String cause) {
                if (!cause.equals(getContext().getResources().getString(R.string.get_data_error)) && !cause.equals(getContext().getResources().getString(R.string.please_login_text)))
                    ToastUtil.makeText(getContext(), cause, Toast.LENGTH_SHORT).show();
                if (refreshLayout != null) refreshLayout.setRefreshing(false);
                PreferenceUtils.putBoolean(getContext(), "hasRepay", false);
                initRepayV();
            }
        });
    }

    private void gotoRepayAct() {
        if (isRepay)
            getNormalRepay();
        else {
            Intent intent = new Intent(getContext(), V3RepayMoneyActivity.class);
            intent.putExtra("deal_id", dealId);
            intent.putExtra("money", newMoney + "");
            intent.putExtra("overdue", overdue);
            intent.putExtra("total_money", (int) Month_need_all_repay_money);
            intent.putExtra("balance", balance);
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
        }
    }


    /**
     * 初始化还钱view
     */
    private void initRepayV() {
        try {

            if (nothingView == null || repayView == null) return;

            HashMap<String, Object> map = new HashMap<>();
            if (PreferenceUtils.getBoolean(getContext(), "is_logined", false) && PreferenceUtils.getBoolean(getContext(), "hasRepay", false)) {
                nothingView.setVisibility(View.GONE);
                repayView.setVisibility(View.VISIBLE);
                map.put(Const.KEY.REPAY_TYPE, 1);
            } else {
                nothingView.setVisibility(View.VISIBLE);
                repayView.setVisibility(View.GONE);
                map.put(Const.KEY.REPAY_TYPE, 0);
            }
            EventBus.getDefault().post(new OnRepayEventMsg(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        api.detachView();
        api = null;
    }


    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void HomeEventBus(OnHomeEventMsg msg) {
        Map<String, String> map = msg.getMsg();
        String type = msg.getMsg().get("type");
        if (type.equals(Const.SendType.UPDATE_REPAY)) {  //更新
            getRepayInfo(null);
        }
        if (type.equals(Const.SendType.SWITCH_PAGE)) { //切换界面
            int currentIndex = Integer.parseInt(map.get("currentIndex"));
            if (currentIndex == 1) {
                initRepayView();
            }
        }
        if (type.equals(Const.SendType.LOGOUT)) {
            nothingView.setVisibility(View.VISIBLE);
            repayView.setVisibility(View.GONE);
        } else if (type.equals(Const.SendType.LOGIN)) {
            getRepayInfo(null);
        }
    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {
        if (mRepaySwipeRefresh != null) {
            mRepaySwipeRefresh.setRefreshing(false);
        }

    }

    @Override
    public void onRequestStart() {
        if (mRepaySwipeRefresh != null) {
            mRepaySwipeRefresh.setRefreshing(true);
        }
    }

    private ArrayList<String> explainList;

    @Override
    public void getRepayDialogSuccess(RepayStatusDialogModel item) {

        explainList = item.data.explain;
        if (item.data.is_alerts == 0 && isFirstDialog) {
            isFirstDialog = false;
            return;
        }
        if (item.data.order_status == 4) {
            gotoRepayAct();
            return;
        }
        //订单状态：0 - 待确认、 1 - 失败、 2 - 成功、4 - 无订单
//        "is_alerts": 1,  //是否需要弹窗：0 - 否，1 - 是
        if (item.data.order_status == 1) {
            gotoRepayAct();
        } else if (item.data.order_status == 2) {
            getRepayInfo(mRepaySwipeRefresh);
        } else if (item.data.order_status == 0) {
            notice_sn = item.data.notice_sn;
            if (item.data.is_alerts == 0) {
                if (item.data.is_repay == 2) {
                    gotoRepayAct();
                } else if (item.data.is_repay == 1||item.data.is_repay == 3) {
                    gotoShenhe(explainList);
                }

            } else if (item.data.is_alerts == 1) {
                isFirstDialog = false;
                Dialog.showConfirmDialog(getContext(), new Dialog.DialogDefaultClickListener() {
                    //                确认支付成功
                    @Override
                    public void confirm() {
                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                    }

                    //                点击支付失败
                    @Override
                    public void cancel() {
                        Dialog.showDefaultDialog(getContext(), "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
//                            点击返回，显示上一个Dialog;
                                Dialog.showConfirmDialog(getContext(), new Dialog.DialogDefaultClickListener() {
                                    @Override
                                    public void confirm() {
                                        api.confirmDialog(item.data.notice_id, api.SUCCESS);
                                    }

                                    @Override
                                    public void cancel() {
                                        Dialog.showDefaultDialog(getContext(), "提示", "确定支付失败吗？", "确定", "返回", false, new Dialog.DialogDefaultClickListener() {
                                            @Override
                                            public void confirm() {

                                            }

                                            @Override
                                            public void cancel() {
                                                api.confirmDialog(item.data.notice_id, api.FAILED);
                                            }
                                        });
                                    }
                                });
                            }

                            @Override
                            public void cancel() {
                                //                            点击确认，支付失败;
                                api.confirmDialog(item.data.notice_id, api.FAILED);
                            }
                        });
                    }
                });
            }
        }

    }

    @Override
    public void confirmDialogSuccess(ConfirmDilaogModel item, String confirm) {
        if (confirm.equals(api.FAILED)) {
            gotoRepayAct();
        } else if (confirm.equals(api.SUCCESS)) {
            gotoShenhe(explainList);
        }
    }

    private void gotoShenhe(ArrayList<String> explain) {
        Intent intent = new Intent(getContext(), ShenHeActivity.class);
        intent.putExtra("deal_id", dealId);
        intent.putExtra("money", newMoney + "");
        intent.putExtra("overdue", overdue);
        intent.putExtra("total_money", (int) Month_need_all_repay_money);
        intent.putExtra("balance", balance);
        intent.putExtra("order", notice_sn);
        intent.putStringArrayListExtra("explain", explain);

        getActivity().startActivity(intent);
        getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
    }
}
